package com.fxnotes.book.utils;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class BusEventListener<T> implements Listener {

    private CountDownLatch latch = new CountDownLatch(1);
    private final Class<T> type;

    public BusEventListener(Class<T> type, EventBus eventBus) {
        this.type = type;
        eventBus.register(this);
    }

    @Subscribe
    public void onEvent(T event) {
        if (event.getClass() == type) {
            latch.countDown();
        }
    }

    @Override
    public boolean waitFor(Event event, int timeout, TimeUnit timeUnit) {
        event.trigger();
        try {
            latch.await(timeout, timeUnit);
        } catch (InterruptedException ex) {
        }

        return latch.getCount() == 0;
    }

    public static <T> boolean waitForEvent(Class<T> type, EventBus eventBus, Event event, int timeout, TimeUnit timeUnit) {
        return new BusEventListener<>(type, eventBus).waitFor(event, timeout, timeUnit);
    }
}
